import tkinter as tk
from tkinter import filedialog
from typing import List, Dict
import json
from loguru import logger
from process_for_editor import process_csv


class TextEditor:
    def __init__(self, root):
        self.root = root
        self.root.title("摘要case分析器")
        self.text_widget = tk.Text(self.root)
        self.text_widget.pack()
        self.load_button = tk.Button(self.root, text="读取数据（csv）", command=self.load_data)
        self.load_button.pack()
        self.next_button = tk.Button(self.root, text="下一个", command=self.load_next)
        self.next_button.pack()
    
    def load_data(self):
        file_path = filedialog.askopenfilename(filetypes=[("CSV Files", "*.csv")])
        if file_path:
            self.load_csv_data(file_path)

    def load_csv_data(self, file_path:str):
        self.data = process_csv(file_path)
        self.current_index = 0
        self.display_current_data()

    def display_current_data(self):
        self.clear_highlight()
        data = self.data[self.current_index]
        query = data.get("query", "").replace('\n', '')
        snippet = data.get("snippet", "").replace('\n', '')
        url = data.get("url", "").replace('\n', '')
        core_content = data.get("core_content", "")
        highlight_info = data.get("hilight_info", [])
        content = f"query: {query}\n\nsnippet: {snippet}\n\nurl: {url}\n\n{core_content}"
        # content = "1937年7月7日，日军进攻卢沟桥。\n 　　卢沟桥横跨永定河，属河北省宛平县管辖，距北平仅30里，为捍卫北平的屏障。驻守在平津一带的中国军队是第二十九军，总兵力约有10万人。\n 　　7月7日夜10时，驻丰台日军河边旅团第一联队第三大队第八中队，由中队长清水节郎率领，在卢沟桥以北地区举行以攻取卢沟桥为假想目标的军事演习，"
        self.text_widget.delete(1.0, tk.END)
        self.text_widget.insert(tk.END, content)
        self.highlight_text(highlight_info)

    def highlight_text(self, highlight_info:List[Dict]):
        # {'row': row, 'col_start': col_start, 'col_end': col_end}
        for info in highlight_info:
            row = info['row']
            col_start = info['col_start']
            col_end = info['col_end']
            logger.info(("highlight", f"{row + 6}.{col_start}", f"{row + 6}.{col_end}"))
            self.text_widget.tag_add("highlight", f"{row + 6}.{col_start}", f"{row + 6}.{col_end}")
            self.text_widget.tag_config("highlight", background="red")

    def clear_highlight(self):
        for tag in self.text_widget.tag_names():
            self.text_widget.tag_remove(tag, 1.0, tk.END)

    def load_next(self):
        if hasattr(self, 'data') and self.current_index < len(self.data) - 1:
            self.current_index += 1
            self.display_current_data()

if __name__ == '__main__':
    root = tk.Tk()
    editor = TextEditor(root)
    root.mainloop()
